<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link https://swoft.org
 * @document https://swoft.org/docs
 * @contact group@swoft.org
 * @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Http\Controller\Admin;

use App\Exception\HttpExecption;
use App\Model\Logic\LoginLogic;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Http\Message\Request;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\Middleware;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use Swoft\Http\Server\Annotation\Mapping\RequestMethod;
use Swoft\Http\Session\HttpSession;
use App\Http\Middleware\CheckLoginMiddleware;
/**
 * Class LoginController
 *
 * @Controller(prefix="/admin")
 * @package App\Http\Controller
 */
class LoginController{
    /**
     * @Inject()
     * @var LoginLogic
     */
    private $loginlogic;
    /**
     * 加载登页面
     * @RequestMapping(route="login", method=RequestMethod::GET)
     */
    public function index()
    {
        //判断是否登录
        if($this->loginlogic->checkLoginStatus()){
            return context()->getResponse()->redirect("/admin");
        }
        return view("admin/login/login");
    }

    /**
     * @RequestMapping("dologin",method={RequestMethod::POST})
     * @param Request $request
     * @return array|mixed|string
     * @throws HttpExecption
     * @throws \Swoft\Validator\Exception\ValidatorException
     */
    public function login(Request $request){
        if(!$request->isAjax()){
            throw new HttpExecption('请求失败',1);
        }
        $data = $request->post();
        //登录验证
        $this->loginlogic->checkLogin($data);
    }

    /**
     * 退出
     * @RequestMapping("logout")
     * @Middleware(CheckLoginMiddleware::class)
     * @return void
     * @throws HttpExecption
     */
    public function logout(){
        if(!context()->getRequest()->isAjax()){
            throw new HttpExecption("请求异常",1);
        }
        if(HttpSession::current()->delete("userid") && HttpSession::current()->delete("username")){
            throw new HttpExecption("已退出登录",0);
        }
    }
}
